package com.guli.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.guli.common.to.mq.SeckillOrderTo;
import com.guli.common.utils.R;
import com.guli.common.vo.MemberResponseVo;
import com.guli.gulimall.seckill.feign.CouponFeignService;
import com.guli.gulimall.seckill.feign.ProductFeignService;
import com.guli.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.guli.gulimall.seckill.service.SeckillService;
import com.guli.gulimall.seckill.to.SecKillSkuRedisTo;
import com.guli.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.guli.gulimall.seckill.vo.SeckillSkuVo;
import com.guli.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    //活动缓存前缀
    private final String SESSIONS_CAHCE_PREFIX = "seckill:sessions:";
    //商品缓存前缀
    private final String SKUKILL_CAHCE_PREFIX = "seckill:skus";
    //商品信号量前缀
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//商品随机码

    @Override
    public void uploadSeckillSkuLatest3Day() {
        //1.扫描最近三天所有需要参与秒杀的活动
        R r = couponFeignService.getLates3DaySession();
        if (r.getCode() == 0) {
            List<SeckillSessionsWithSkus> sessionDatas = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //1.缓存活动信息
            saveSessionInfo(sessionDatas);
            //2.缓存活动的关联商品信息
            saveSessionSkuInfo(sessionDatas);
        }
    }

    /**
     * blockHandler = "blockHandler" ，指定方法降级的时候调用
     * fallbackClass =  "",   fallback = "" ,针对所有类型的异常
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        //1.确定当前时间属于哪个秒杀时间
        long time = new Date().getTime();
        String key = SESSIONS_CAHCE_PREFIX + "*";
        try (Entry entry = SphU.entry("seckillSkus")) {
            // sentinel 被保护的业务逻辑
            Set<String> keys = redisTemplate.keys(key);
            for (String k : keys) {
                String replace = k.replace(SESSIONS_CAHCE_PREFIX, "");
                String[] s = replace.split("_");
                Long startTime = Long.parseLong(s[0]);
                Long endTime = Long.parseLong(s[1]);
                if (time >= startTime && time <= endTime) {
                    //2.获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(k, -100, 100);//取-100 到 100的数据
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CAHCE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null && list.size() > 0) {
                        List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                            SecKillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SecKillSkuRedisTo.class);
//                        redisTo.setRandomCode(null);//当前秒杀开始需要随机码
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException ex) {
            // 资源访问阻止，被限流或被降级
            // 在此处进行相应的处理操作
            log.error("资源被限制" + ex.getMessage());
        }
        return null;
    }

    // blockHandler 函数，原方法调用被限流/降级/系统保护的时候调用
    public List<SecKillSkuRedisTo> blockHandler(BlockException ex) {
        log.error("getCurrentSeckillSkusResource 被限流了。。");
        return null;
    }

    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1.找到所有参与秒杀的商品key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CAHCE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String reg = "\\d-" + skuId;
            for (String key : keys) {
                //7-6
                boolean matches = Pattern.matches(reg, key);
                if (matches) {
                    String s = hashOps.get(key);
                    if (StringUtils.isNotBlank(s)) {
                        SecKillSkuRedisTo redisTo = JSON.parseObject(s, SecKillSkuRedisTo.class);
                        //随机码
                        Long startTime = redisTo.getStartTime();
                        Long endTime = redisTo.getEndTime();
                        long now = new Date().getTime();
                        if (now >= startTime && now <= endTime) {
                            //在秒杀时间内，返回随机码
                        } else {
                            //不在秒杀时间不返回随机码
                            redisTo.setRandomCode(null);
                        }
                        return redisTo;
                    }
                }
            }
        }
        return null;
    }

    //todo 上架秒杀商品的时候,每一个数据都有过期时间.
    //todo 秒杀后续的流程,简化了收货地址等信息.
    @Override
    public String seckill(String killId, String key, Integer num) {
        long l = System.currentTimeMillis();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        //1.是否登录，拦截器已经帮我们验证了
        //2.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CAHCE_PREFIX);
        String s = hashOps.get(killId);
        if (StringUtils.isEmpty(s)) {
            return null;
        } else {
            SecKillSkuRedisTo redisTo = JSON.parseObject(s, SecKillSkuRedisTo.class);
            //3.校验合法性
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long millis = System.currentTimeMillis();
            //校验时间合法性
            if (millis >= startTime && millis <= endTime) {
                //校验随机码和商品id是否正确
                String randomCode = redisTo.getRandomCode();
                String killId2 = redisTo.getPromotionSessionId() + "-" + redisTo.getSkuId();
                if (randomCode.equals(key) && killId.equals(killId2)) {
                    //校验购物数量是否合理
                    Integer seckillLimit = redisTo.getSeckillLimit().intValue();
                    if (num <= seckillLimit) {
                        //校验这个人是否已经买过了，幂等性；只要秒杀成功，就去redis占位，userId_SessionId_skuId
                        String redisKey = memberResponseVo.getId() + "-" + killId2;
                        //自动过期时间
                        Long ttl = endTime - System.currentTimeMillis(); //过期的时间
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功，说明这个人从来没买过
                            //获取信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
//                            try {
                            //要等待
//                                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                            //} catch (InterruptedException e) {
//                                //秒杀失败
//                                return null;
//                            }
                            //不需要等待,拿不到就走
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //秒杀成功，快速下单，发送MQ消息
                                String orderSn = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(orderSn);
                                orderTo.setMemberId(memberResponseVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                orderTo.setSkuId(redisTo.getSkuId());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                Long m = System.currentTimeMillis() - l;
                                log.info("秒杀耗时:{}ms", m);
                                return orderSn;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 缓存活动信息
     *
     * @param sessions
     */
    private void saveSessionInfo(List<SeckillSessionsWithSkus> sessions) {
        if (sessions != null && sessions.size() > 0) {
            sessions.stream().forEach(session -> {
                Long startTime = session.getStartTime().getTime();
                Long endTime = session.getEndTime().getTime();
                //活动开始时间_活动结束时间
                String key = SESSIONS_CAHCE_PREFIX + startTime + "_" + endTime;
                Boolean hasKey = redisTemplate.hasKey(key);//防止重复上架
                if (!hasKey) {
                    //商品id集合 场次-商品id
                    List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "-" + item.getSkuId()).collect(Collectors.toList());
                    //缓存活动信息
                    redisTemplate.opsForList().leftPushAll(key, collect);
                }
            });
        }
    }

    /**
     * 缓存活动的关联商品信息
     *
     * @param sessions
     */
    private void saveSessionSkuInfo(List<SeckillSessionsWithSkus> sessions) {
        if (sessions != null) {
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CAHCE_PREFIX);
            sessions.stream().forEach(session -> {

                session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    // 1.商品的随机码
                    String randomCode = UUID.randomUUID().toString().replace("-", "");
                    //防止重复上架
                    if (!ops.hasKey(seckillSkuVo.getPromotionSessionId() + "-" + seckillSkuVo.getSkuId())) {
                        // 2.缓存商品
                        SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);
                        // 3.sku的基本数据 sku的秒杀信息
                        R info = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                        if (info.getCode() == 0) {
                            SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfo(skuInfo);
                        }
                        // 4.设置当前商品的秒杀信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());

                        redisTo.setRandomCode(randomCode);

                        ops.put(seckillSkuVo.getPromotionSessionId() + "-" + seckillSkuVo.getSkuId(), JSON.toJSONString(redisTo));
                        // 如果当前这个场次的商品库存已经上架就不需要上架了
                        // 5.使用库存作为分布式信号量  限流
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                    }
                });
            });
        }
    }

}
